﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using SangoBang;
using System.Xml;
namespace TestProject1
{
    class MessageListener
    {
        private string mGuid;
        private EventController mEventController;
        private string mUsername;
        bool mStart;
        Queue<String> mMessageQueue = new Queue<string>();
        Thread mListenerThread;
        public void StartListen(String guid, EventController ec,string username) 
        {
            mGuid = guid;
            mEventController = ec;
            mUsername = username;
            mStart = true;
            mListenerThread = new Thread(this.DoListen);
            mListenerThread.Start();
        }
        private void DoListen() 
        {
            string msg;

            while (mStart) 
            {
                msg = mEventController.GetMsg(mGuid);
                System.Console.WriteLine(mUsername + " msg: " + msg);
                mMessageQueue.Enqueue(msg);
            }
        }
        public string ExpectMessage(string expectType)
        {
            Thread.Sleep(10);
            while (mMessageQueue.Count != 0) 
            {
                string msg = mMessageQueue.Dequeue();
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.LoadXml(msg);
                XmlElement MsgElement = xmldoc.DocumentElement;
                string type = MsgElement.GetAttribute("type");
                if (type == expectType)
                    return msg;
                Thread.Sleep(100);
            }
            return null;
        }
        public string ExpectMessage(string expectType, string stopType)
        {
            Thread.Sleep(10);
            while (mMessageQueue.Count != 0)
            {
                string msg = mMessageQueue.First();
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.LoadXml(msg);
                XmlElement MsgElement = xmldoc.DocumentElement;
                string type = MsgElement.GetAttribute("type");
                if (type == stopType)
                    return null;
                mMessageQueue.Dequeue();                
                if (type == expectType)
                    return msg;
                
                Thread.Sleep(10);
            }
            return null;
        }
    }
}
